# alarm_core.py
import threading
import time
import datetime
from audio_player import play_alarm_sound


class AlarmClock:
    def __init__(self, gui):
        self.gui = gui
        self.running = True
        self.thread = threading.Thread(target=self.check_alarms, daemon=True)
        self.thread.start()

    def check_alarms(self):
        """后台循环检查当前时间是否匹配闹钟"""
        while self.running:
            now = datetime.datetime.now()
            current_time_str = now.strftime("%H:%M")
            current_minute = now.minute

            # 检查固定时间闹钟
            for alarm in self.gui.alarms[:]:
                if alarm['type'] == 'fixed' and alarm['time'] == current_time_str and not alarm.get('triggered_today', False):
                    self.trigger_alarm(alarm)
                    alarm['triggered_today'] = True

            # 检查每小时分钟闹钟
            for alarm in self.gui.alarms[:]:
                if alarm['type'] == 'hourly' and alarm['minute'] == current_minute:
                    self.trigger_alarm(alarm)

            # 每天午夜重置 fixed 闹钟状态
            if now.hour == 0 and now.minute == 0:
                for alarm in self.gui.alarms:
                    if alarm['type'] == 'fixed':
                        alarm['triggered_today'] = False

            time.sleep(30)  # 每30秒检查一次

    def trigger_alarm(self, alarm):
        """触发闹钟：播放声音 + 弹窗"""
        def show_alert():
            play_alarm_sound(self.gui.alarm_sound_file)

            alarm_desc = alarm.get('time', f"每小时第{alarm['minute']}分钟")
            msg = f"⏰ 闹钟响了！\n时间：{alarm_desc}"
            self.gui.show_alarm_message(msg)

            # 停止音乐（如果使用 pygame）
            try:
                import pygame
                pygame.mixer.music.stop()
            except:
                pass

        # 在主线程中安全调用 GUI
        self.gui.root.after(0, show_alert)

    def stop(self):
        self.running = False